﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using FunstreamTV.Model;
using FunstreamTV.ViewModel;

namespace FunstreamTV.Tools
{
    public class Requester
    {


        public async Task<TResponse> Get<TResponse>(string request)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(request);
            var json = String.Empty;
            if (response.IsSuccessStatusCode)
                json = await response.Content.ReadAsStringAsync();

            var result = Serializer.Deserialize<TResponse>(json);
            return result;
        }

        public async Task<Response<TResponse>> Post<TResponse, TRequest>(string method, TRequest body)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var json = Serializer.Serialize(body);
            var content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            string token;
            try
            {
                var user = await BaseViewModel.GetUser();
                token = user.token;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                token = String.Empty;
            }
            if (!String.IsNullOrEmpty(token))
                content.Headers.Add("Token", "Bearer " + token);
            var response = await client.PostAsync(BaseViewModel.ServerUrl + "/api" + method, content);
            json = await response.Content.ReadAsStringAsync();
            Debug.WriteLine(json);
            
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var result = Serializer.Deserialize<TResponse>(json);
                return new Response<TResponse> { Item = result };
            }
            else
            {
                var result = Serializer.Deserialize<ServerError>(json);
                return new Response<TResponse> { Item = default(TResponse), Message = result.message };
            }

        }
    }
}
